package  com.ruoyi.merchant.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;

import com.ruoyi.merchant.domain.OrderReview;
import com.ruoyi.merchant.domain.vo.ReplyReviewRequest;
import com.ruoyi.merchant.domain.vo.ReviewStatisticsVO;
import com.ruoyi.merchant.service.IMerchantRatingService;
import com.ruoyi.merchant.service.IOrderReviewService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 商家端-评价管理Controller
 */
@RestController
@RequestMapping("/merchant/review")
public class MerchantReviewController extends BaseController {

    @Autowired
    private IOrderReviewService orderReviewService;

    @Autowired
    private IMerchantRatingService merchantRatingService;

    /**
     * 手动更新商家评分
     */
    @Log(title = "评价管理-更新评分", businessType = BusinessType.UPDATE)
    @PutMapping("/updateRating")
    public AjaxResult updateRating() {
        // 从token中获取当前登录商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        log.info("商家手动更新评分，商家ID：{}", merchantId);

        try {
            BigDecimal newRating = merchantRatingService.calculateAndUpdateRating(merchantId);

            return AjaxResult.success("评分更新成功", newRating);
        } catch (Exception e) {
            log.error("手动更新商家评分失败，商家ID：{}", merchantId, e);
            return error("评分更新失败：" + e.getMessage());
        }
    }

    /**
     * 仅查看计算后的评分（不更新数据库）
     */
    @GetMapping("/previewRating")
    public AjaxResult previewRating() {
        // 从token中获取当前登录商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        try {
            BigDecimal calculatedRating = merchantRatingService.calculateRating(merchantId);
            return success(calculatedRating);
        } catch (Exception e) {
            log.error("计算评分失败，商家ID：{}", merchantId, e);
            return error("计算失败：" + e.getMessage());
        }
    }

    /**
     * 查询评价列表
     */
    @GetMapping("/list")
    public TableDataInfo list(OrderReview orderReview) {
        // 从token中获取当前登录商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        orderReview.setMerchantId(merchantId);

        startPage();
        List<OrderReview> list = orderReviewService.selectMerchantReviewList(orderReview);
        return getDataTable(list);
    }

    /**
     * 获取评价详情
     */
    @GetMapping("/detail/{reviewId}")
    public AjaxResult getInfo(
            @PathVariable("reviewId") Long reviewId) {
        OrderReview review = orderReviewService.selectReviewById(reviewId);

        // 验证商家权限
        if (review == null) {
            return error("评价不存在");
        }

        // 从token中获取当前登录商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (!review.getMerchantId().equals(merchantId)) {
            return error("无权查看该评价");
        }

        return success(review);
    }

    /**
     * 回复评价
     */
    @Log(title = "评价管理", businessType = BusinessType.UPDATE)
    @PutMapping("/reply")
    public AjaxResult reply(@Validated @RequestBody ReplyReviewRequest request) {
        // 验证商家权限
        OrderReview review = orderReviewService.selectReviewById(request.getReviewId());
        if (review == null) {
            return error("评价不存在");
        }

        // 从token中获取当前登录商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (!review.getMerchantId().equals(merchantId)) {
            return error("无权回复该评价");
        }

        return toAjax(orderReviewService.replyReview(request));
    }

    /**
     * 查询评价统计
     */
    @GetMapping("/statistics")
    public AjaxResult statistics() {
        // 从token中获取当前登录商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        ReviewStatisticsVO statistics = orderReviewService.selectReviewStatistics(merchantId);
        return success(statistics);
    }
}
